/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2011 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;
using System.Windows;
using System.Linq;
using AWZhome.NQ.CommonServices.Fluent;

namespace AWZhome.NQ.CommonServices
{
	[NQExportedService(Category = NQHostMode.GUI)]
	[NQServiceAttachment(NQCoreAttachLists.ServiceManager_PostServiceInit)]
	internal class ComponentSupervisorService
	{
		[NQServiceInvokeMethod]
		public void InvokeService()
		{
			IConfigManager servPersist = ServiceCore
				.Get<Services.IConfigService>()
				.To;
			IResourceManager servRes = ServiceCore
				.Get<Services.IResourceService>()
				.To;

			bool passiveComponentSupervising = servPersist.GetComponentSetting("NQCS", "passiveComponentSupervising").AsBoolean(false);
			var availableComponents = new HashSet<string>(ServiceCore.AllComponents);

			// Run through all formerly known components and check if they are still there
			IList<ConfigData> knownComponents = servPersist.GetComponentListSetting("NQCS", "knownComponents");
			if (knownComponents != null)
			{
				foreach (var data in knownComponents)
				{
					if (ServiceCore.ComponentMetaInfo(data.AsString()) == null)
					{
						// Log information
						ServiceCore.Log.Info("Detected deleted component " + data.AsString() + ".");

						// There used to be a component, which is not here anymore
						if (MessageBox.Show(
							servRes.GetResString("NQCS", "ComponentSupervisor.Msg.AskForDeletingSettings", data.AsString()),
							servRes.GetResString("NQCS", "ComponentSupervisor.Msg.AskForDeletingSettings.Title"),
							MessageBoxButton.YesNo, MessageBoxImage.Question)
							== MessageBoxResult.No)
						{
							servPersist.RemoveComponentGroup(data.AsString(), false);
						}
					}

					if (availableComponents.Contains(data.AsString()))
					{
						availableComponents.Remove(data.AsString());
					}
				}
			}

			// All components existing in the HashSet are new components!
			foreach (string newComponent in availableComponents)
			{
				// Add the components update URL to internal list
				INQComponentInfo newComponentInfo = ServiceCore.ComponentMetaInfo(newComponent);

				// Log information
				ServiceCore.Log.Info("Detected new component " + newComponent + " (" + newComponentInfo.DisplayName + ").");

				IList<ConfigData> updateURLList = Configuration.List("updateURLs")
					.InGroup("NQCS")
					.OfComponents()
					.Get;
				if (updateURLList == null)
				{
					updateURLList = new List<ConfigData>();
				}
				string updaterURL = newComponentInfo.UpdaterURL;
				if (!String.IsNullOrEmpty(updaterURL))
				{
					if (!updateURLList.Select(conf => conf.AsString()).Contains(updaterURL))
					{
						updateURLList.Add(new ConfigData().FromString(updaterURL));
						Configuration.List("updateURLs")
							.InGroup("NQCS")
							.OfComponents()
							.SetGlobal(updateURLList);
					}
				}
			}

			// Now build a new list with all loaded components and save it
			IList<ConfigData> complist =
				new List<ConfigData>(ServiceCore.AllComponents.Select(c => new ConfigData().FromString(c)));
			servPersist.SetComponentListSetting("NQCS", "knownComponents", complist, false);
			Configuration.List("knownComponents")
				.InGroup("NQCS")
				.OfComponents()
				.SetGlobal(complist);
		}
	}
}
